package com.f1ashback.bus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.f1ashback.bus.Qo.UserQo;
import com.f1ashback.bus.Vo.UserVo;
import com.f1ashback.bus.common.AjaxResult;
import com.f1ashback.bus.common.JwtUtils;
import com.f1ashback.bus.common.ThreadUtils;
import com.f1ashback.bus.entity.User;
import com.f1ashback.bus.mapper.FeedBackMapper;
import com.f1ashback.bus.mapper.UserMapper;
import com.f1ashback.bus.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FeedBackMapper feedBackMapper;

    @Override
    public AjaxResult applogin(User user) {
        User userLogin = userMapper.selectByUserName(user.getUsername());
        if (userLogin == null) {
            log.info("当前登录用户不存在");
            return AjaxResult.error("用户未注册");
        }
        if (!(userLogin.getUsername().equals(user.getUsername()) && userLogin.getPassword().equals(user.getPassword()))) {
            log.info("当前登录用户名为:{},账户或密码不正确", userLogin.getUsername());
            return AjaxResult.error("用户名或密码不正确");
        }
        if (userLogin.getAuth() == 0) {
            log.info("管理员登录成功");
        } else {
            log.info("登录成功");
        }
        String token = getToken(userLogin);
        log.warn("UserToken:{}", token);
        ThreadUtils.setUserId(userLogin.getUserId());
        return AjaxResult.success("登录成功", userLogin, token);
    }

    @Override
    public AjaxResult add(User user) {
        user.setUserId(setUserId(user.getUsername()));
        user.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        if (user.getPassword() != null && user.getPassword().length() < 6) {
            return AjaxResult.error("密码长度不能小于6位!");
        }
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            System.out.println(e);
            return AjaxResult.error("添加失败,用户名已存在!");
        }
        return AjaxResult.success("添加成功");
    }

    @Override
    public AjaxResult update(User user) {
        if (user.getPassword() != null && user.getPassword() != "" && user.getPassword().length() < 6) {
            return AjaxResult.error("密码长度不能小于6位!");
        }
        Integer i = userMapper.updateByUserName(user);
        if (i <= 0 && i != -99) {
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult delete(Long userId) {
        log.warn(userId.toString());
        try {
            userMapper.deleteById(userId);
        } catch (Exception e) {
            return AjaxResult.error("删除失败");
        }
        feedBackMapper.deleteByUserId(userId);
        return AjaxResult.success("删除成功");
    }

    @Override
    public AjaxResult register(User user) {
        if (userMapper.selectByUserName(user.getUsername()) != null) {
            return AjaxResult.error("用户已存在");
        }
        user.setUserId(setUserId(user.getUsername()));
        user.setAuth(1);
        user.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        userMapper.insert(user);
        return AjaxResult.success("注册成功");
    }

    @Override
    public String getToken(User user) {
        Map<String, Long> map = new HashMap<>();
        map.put("userId", user.getUserId());
        map.put("userAuth", Long.valueOf(user.getAuth()));
        String token = JwtUtils.getToken(map);
        return token;
    }

    @Override
    public User getOneUser(Long userId) {
        if (userId == null) {
            log.warn("未获取到UserId");
            log.warn("UserServiceUserId:{}", userId);
            return null;
        }
        log.warn(userId.toString());
        User user = null;
        if (userId != null) {
            user = userMapper.selectByUserId(userId);
        }
        if (user != null) {
            return user;
        }
        return null;
    }

    @Override
    public AjaxResult login(User user) {
        User userLogin = null;
        log.warn(user.getUsername());
        try {
            userLogin = userMapper.selectByUserName(user.getUsername());
        } catch (Exception e) {
            log.warn("用户未输入用户名或密码");
            return AjaxResult.error("请输入用户名及密码！");
        }
        if (userLogin == null) {
            log.info("当前登录用户不存在");
            return AjaxResult.error("用户不存在");
        }
        if (!(userLogin.getUsername().equals(user.getUsername()) && userLogin.getPassword().equals(user.getPassword()))) {
            log.info("当前登录用户名为:{},账户或密码不正确", userLogin.getUsername());
            return AjaxResult.error("用户名或密码不正确");
        }
        if (userLogin.getAuth() != 0) {
            return AjaxResult.error("您不是管理员");
        }
        String token = getToken(userLogin);
        ThreadUtils.setUserId(userLogin.getUserId());
        return AjaxResult.success("登录成功！", userLogin, token);
    }

    @Override
    public AjaxResult listUser() {
        log.warn("获取用户列表");
        List<UserVo> vores = new ArrayList<>();
        Map<String, List<UserVo>> res = new HashMap<>();
        List<User> list = userMapper.list();
        for (User user : list) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            if (user.getAuth() == 0) {
                userVo.setAuth("管理员");
            } else {
                userVo.setAuth("用户");
            }
            vores.add(userVo);
        }
        res.put("res", vores);
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult mupdate(UserVo user) {
        Integer i = 0;
        User user1 = new User();
        BeanUtils.copyProperties(user, user1);
        if (user.getAuth().equals("管理员")) {
            user1.setAuth(0);
        } else if (user.getAuth().equals("用户")) {
            user1.setAuth(1);
        } else if (Integer.valueOf(user.getAuth()) == 0) {
            user1.setAuth(0);
        } else if (Integer.valueOf(user.getAuth()) == 1) {
            user1.setAuth(1);
        }
        try {
            i = userMapper.updateById(user1);
        } catch (Exception e) {
            return AjaxResult.error("修改失败!");
        }
        if (i > 0) {
            return AjaxResult.success("修改成功！");
        }
        return AjaxResult.error("修改失败！");
    }

    @Override
    public AjaxResult queryUser(UserQo userQo) {
        Map<String, List<UserVo>> res = new HashMap<>();
        List<UserVo> voList = new ArrayList<>();
        User queryUser = new User();
        BeanUtils.copyProperties(userQo, queryUser);
        if (userQo.getAuth() != null && userQo.getAuth() != "" && userQo.getAuth().equals("管理员")) {
            queryUser.setAuth(0);
        } else if (userQo.getAuth() != null && userQo.getAuth() != "" && userQo.getAuth().equals("用户")) {
            queryUser.setAuth(1);
        } else {
            queryUser.setAuth(null);
        }
        List<User> list = userMapper.queryUser(queryUser);
        for (User user : list) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            if (user.getAuth() == 0) {
                userVo.setAuth("管理员");
            } else {
                userVo.setAuth("用户");
            }
            voList.add(userVo);
        }
        res.put("res", voList);
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult getAllUserName() {
        Map<String,List<String>> res = new HashMap<>();
        List<String> usernames = userMapper.selectAllUserName();
        res.put("res",usernames);
        return AjaxResult.success(res);
    }

    private Long setUserId(String username) {
        String userN = username + "f1ash6ack";
        byte[] bytes = userN.getBytes();
        int b = 0;
        for (byte aByte : bytes) {
            b += aByte;
        }
        if (b < 0) {
            b = -b;
        }
        Long res = 60000000l + Long.valueOf(String.valueOf(Long.valueOf(b) + System.currentTimeMillis()).substring(6));
        return res;
    }
}
